package inet.app.vod.activity.news;

import inet.app.vod.activity.R;
import inet.app.vod.activity.common.BaseActivity;
import inet.app.vod.activity.film.IPhimActivity;
import inet.app.vod.activity.film.IPhimDetailActivity;
import inet.app.vod.adapter.NewCategoryAdapter;
import inet.app.vod.adapter.SlideImagesAdapter;
import inet.app.vod.config.AppConstants;
import inet.app.vod.listeners.SlideImageClickListener;
import inet.app.vod.net.http.VolleyClient;
import inet.app.vod.net.http.VolleyListener;
import inet.app.vod.object.CategoryModel;
import inet.app.vod.object.MovieModel;
import inet.app.vod.object.NewModel;
import inet.app.vod.object.ResultJsonModel;
import inet.app.vod.object.SlideObject;
import inet.app.vod.parser.Parse;
import inet.app.vod.util.MyUtil;
import inet.app.vod.view.MyViewPagerIndicator;

import java.util.ArrayList;
import java.util.List;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListViewHorizontalScroll;
import com.handmark.pulltorefresh.library.internal.CustomListViewForHorizontalScroll;
import com.inet.app.framework.intentutil.LaunchIntent;
import com.inet.app.framework.util.Log;
import com.inet.app.framework.widget.MyToast;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

public class INewsCategoryActivity extends BaseActivity {

	private PullToRefreshListViewHorizontalScroll mPullView;
	private CustomListViewForHorizontalScroll mListView;
	private ViewPager mSlideImages;
	private MyViewPagerIndicator mIndicators;
	private RelativeLayout mSlideLayout;

	private CategoryModel mCategory;
	private SlideImagesAdapter mSlideAdapters;
	private NewCategoryAdapter mAdapter;
	private List<NewModel> mNews = new ArrayList<NewModel>();
	private List<NewModel> mListHot = new ArrayList<NewModel>();
	private int page = AppConstants.START_PAGE;

	private SlideImageClickListener onSlideListener = new SlideImageClickListener() {

		@Override
		public void onSlideClick(SlideObject slide) {
			for (NewModel newModel : mListHot) {
				if (newModel.getId().equals(slide.getId())) {
					Bundle bundle = new Bundle();
					bundle.putSerializable("item_new", newModel);
					LaunchIntent.start(INewsCategoryActivity.this,
							INewsDetailActivity.class, bundle);
					break;
				}
			}
		}
	};

	private OnRefreshListener2<CustomListViewForHorizontalScroll> onRefresh = new OnRefreshListener2<CustomListViewForHorizontalScroll>() {

		@Override
		public void onPullDownToRefresh(
				PullToRefreshBase<CustomListViewForHorizontalScroll> refreshView) {
			requestListItem();
		}

		@Override
		public void onPullUpToRefresh(
				PullToRefreshBase<CustomListViewForHorizontalScroll> refreshView) {
			requestListItem();
		}
	};

	private void initModels() {

		Bundle bundle = getIntent().getExtras();
		if (null != bundle) {
			mCategory = (CategoryModel) bundle.getSerializable("category");
			if (mCategory == null) {
				MyToast.show(this, "Không tìm thấy dữ liệu trong mục này!");
				finish();
				return;
			}
		}
	}

	private void initViews() {
		mPullView = (PullToRefreshListViewHorizontalScroll) findViewById(R.id.news_list);
		mPullView.setPullLabel(getString(R.string.keo_de_tai_them));
		mPullView.setReleaseLabel(getString(R.string.tha_de_bat_dau_tai));
		mPullView.setRefreshingLabel(getString(R.string.dang_tai));
		mPullView.setOnRefreshListener(onRefresh);

		setTitle(mCategory.getName());
		View headerView = LayoutInflater.from(this).inflate(
				R.layout.header_slide_images, null);
		mSlideImages = (ViewPager) headerView.findViewById(R.id.slide_images);
		mSlideLayout = (RelativeLayout) headerView
				.findViewById(R.id.slide_layout);
		mIndicators = (MyViewPagerIndicator) headerView
				.findViewById(R.id.my_indicator);
		mIndicators.setColorDefault(Color.WHITE);
		mListView = mPullView.getRefreshableView();
		mListView.addHeaderView(headerView);

		mListView.setAdapter(mAdapter);
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				NewModel news;
				if (mListHot == null || mListHot.size() == 0) {
					// list view hasn't header view
					news = mNews.get(position - 1);
				} else {
					// list view has header view
					news = mNews.get(position - 2);
				}
				Bundle bundle = new Bundle();
				bundle.putSerializable("item_new", news);
				LaunchIntent.start(INewsCategoryActivity.this,
						INewsDetailActivity.class, bundle);
			}
		});
		mListView.setAdapter(mAdapter);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_inews_category);
		initUIBase();
		initModels();
		initViews();
		requestListItem();
		requestListHot();
	}

	public void requestListItem() {
		int numItemRequest = AppConstants.getPageSize(this);
		VolleyClient.requestItems(AppConstants.NAME_INEWS,
				mCategory.getRemoteId(), numItemRequest, page,
				new VolleyListener(this) {

					@Override
					public void onSuccess(String response) {
						Log.d("success request" + response);
						ResultJsonModel jResult = Parse
								.parseNewListHot(response);
						if (jResult == null) {
							// error parser
							MyUtil.showDialog(
									getString(R.string.khong_the_lay_cac_muc_trong_phan_tin_tuc),
									INewsCategoryActivity.this);
						} else if (jResult.hasError()) {
							// error register
							String error = jResult.getError();
							MyUtil.showDialog(error, INewsCategoryActivity.this);
						} else {
							// save categories to database
							List<NewModel> news = (List<NewModel>) jResult
									.getResult();
							if (news.size() == 0 && page > 1) {
								MyToast.show(INewsCategoryActivity.this,
										"Đã tải hết dữ liệu");
								mPullView.onRefreshComplete();
								return;
							}
							if (page == 1) {
								mNews = news;
							} else {
								mNews.addAll(news);
							}
							showListNews();
							page++;
							saveListNewsToDB();

						}
					}

					@Override
					public void onStart() {
						Log.d("start request");
						showLoading(true);
					}

					@Override
					public void onFinish() {
						Log.d("finish request");
						showLoading(false);
					}

					@Override
					public void onError(VolleyError error) {
						MyUtil.showDialog(
								getString(R.string.khong_the_lay_cac_muc_trong_phan_tin_tuc)
										+ "(" + error.getMessage() + ")",
								INewsCategoryActivity.this);
					}
				});
	}

	public void requestListHot() {
		VolleyClient.requestListHot(AppConstants.NAME_INEWS,
				mCategory.getRemoteId(), new VolleyListener(this) {

					@Override
					public void onSuccess(String response) {
						Log.d("success request" + response);
						ResultJsonModel jResult = Parse
								.parseNewListHot(response);
						if (jResult == null) {
							// error parser
							MyUtil.showDialog(
									getString(R.string.khong_the_lay_cac_muc_trong_phan_tin_tuc),
									INewsCategoryActivity.this);
						} else if (jResult.hasError()) {
							// error register
							String error = jResult.getError();
							MyUtil.showDialog(error, INewsCategoryActivity.this);
						} else {
							// Save categories to database
							mListHot = (List<NewModel>) jResult.getResult();
							saveListHotToDB();
							showListHot();
						}
					}

					@Override
					public void onStart() {
						Log.d("start request");
						findViewById(R.id.view_loading).setVisibility(
								View.VISIBLE);
					}

					@Override
					public void onFinish() {
						Log.d("finish request");
						findViewById(R.id.view_loading)
								.setVisibility(View.GONE);
					}

					@Override
					public void onError(VolleyError error) {
						MyUtil.showDialog(
								getString(R.string.khong_the_lay_tin_tuc_hot),
								INewsCategoryActivity.this);
					}
				});
	}

	private void showListNews() {
		mPullView.onRefreshComplete();
		if (mNews.size() == 0) {
			mPullView.setVisibility(View.GONE);
			TextView status = (TextView) findViewById(R.id.status_text);
			status.setText("Không có bài viết trong " + mCategory.getName());
			status.setVisibility(View.VISIBLE);
			return;
		}
		if (page == AppConstants.START_PAGE) {
			mAdapter = new NewCategoryAdapter(this, mNews);
			mListView.setAdapter(mAdapter);
		} else {
			mAdapter.notifyDataSetChanged();
		}
		int newFirstPos = (page - 1) * AppConstants.getPageSize(this);
		// mListView.smoothScrollToPositionFromTop(newFirstPos + 1, 0);
		mListView.smoothScrollToPosition(newFirstPos + 1);
	}

	private void saveListNewsToDB() {
	}

	private void saveListHotToDB() {
	}

	private void showListHot() {
		if (mListHot == null) {
			return;
		}
		if (mListHot.size() == 0) {
			mListView.removeHeaderView(mSlideLayout);
			return;
		}
		if (mListHot.size() == 1) {
			mIndicators.setVisibility(View.GONE);
		}
		List<SlideObject> slides = new ArrayList<SlideObject>();
		SlideObject slide;
		for (NewModel newModel : mListHot) {
			slide = new SlideObject(newModel.getId(), newModel.getImg(),
					newModel.getTitle());
			slides.add(slide);
		}
		mSlideAdapters = new SlideImagesAdapter(this, slides, onSlideListener);
		mSlideAdapters.showTitle(true);
		mSlideImages.setAdapter(mSlideAdapters);
		mIndicators.attachToViewPager(mSlideImages, new OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
				switch (position) {
				case 0:
					mSlideMenu
							.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
					break;
				default:
					mSlideMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
					break;
				}
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});
	}

	@Override
	public void setTagMenu() {
		mTagMenu = AppConstants.MENU_INEWS;
	}
}
